package com.deanlib.cabinet.ui.recyclerview;

import android.content.Context;
import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @auther Dean
 * @create 2022/3/24
 */
public class HorizontalItemDecoration extends RecyclerView.ItemDecoration{

    private int space = 0;//定义2个Item之间的距离
    private int leftSpace = 0;
    private int rightSpace = 0;

    public HorizontalItemDecoration(Context context, int space){
        this.space = dip2px(context, space);
    }

    public HorizontalItemDecoration(Context context, int space, int leftSpace, int rightSpace){
        this(context, space);
        this.leftSpace = dip2px(context, leftSpace);
        this.rightSpace = dip2px(context, rightSpace);
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
                               @NonNull RecyclerView parent,
                               @NonNull RecyclerView.State state) {
        if (parent.getAdapter()!=null) {
            int position = parent.getChildAdapterPosition(view);
            int totalCount = parent.getAdapter().getItemCount();
            if (position == 0) { //第一个
                outRect.left = leftSpace;
                outRect.right = space / 2;
            } else if (position == totalCount - 1) { //最后一个
                outRect.left = space / 2;
                outRect.right = rightSpace;
            } else { //中间其它的
                outRect.left = space / 2;
                outRect.right = space / 2;
            }
            //super.getItemOffsets(outRect, view, parent, state);
        }
    }

    private int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
